package com.atxwq.shop.manager.utils;

import com.atxwq.shop.model.entity.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 构建树形菜单的工具类
 * @Date 2025/5/12 16:25
 * @Created by 12336
 */

public class MenuHelper {

    /**
     * 使用递归方式构建菜单列表
     * @param sysMenuList
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList){
        List<SysMenu> trees = new ArrayList<>();
        for(SysMenu sysMenu : sysMenuList){
            if(sysMenu.getParentId().longValue() == 0){
                trees.add(findChildren(sysMenu,sysMenuList));
            }
        }
        return trees;
    }

    /**
     * 递归方法查找子节点
     * @param sysMenu
     * @param sysMenuList
     * @return
     */
    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) {
        sysMenu.setChildren(new ArrayList<SysMenu>());
        for(SysMenu it : sysMenuList){
            if(sysMenu.getId().equals(it.getParentId())){
                sysMenu.getChildren().add(findChildren(it,sysMenuList));
            }
        }
        return sysMenu;
    }
}
